# -*- coding: utf-8 -*-
import json
import traceback
import requests
import time


def post(url, data, token, head_args=None):
    headers = {'Content-Type': 'application/json'}
    if token:
        headers['X-TOKEN'] = token
    if head_args:
        for key in head_args.keys():
            headers[key] = head_args.get(key)
    body = json.dumps(data)

    session = requests.session()
    try:
        print("发出请求：\n    url=%s, \n    token=%s \n    data=%s"
              % (url, token, json.dumps(data, ensure_ascii=False)))
        ret = session.post(url=url, data=body, headers=headers, timeout=10)

        result = ret.json()
        print(json.dumps(result, ensure_ascii=False))
        status = result["code"]
        msg = result["msg"]

        if status != 200:
            raise Exception("收到处理失败的答复，code：" + str(status)
                            + ", message: " + msg)

        print("接收到答复信息 code：%s，message：%s \n %s"
              % (status, msg, json.dumps(result, ensure_ascii=False)))
        return result
    except Exception as e:
        print("发生异常：", e)
        print(traceback.format_exc())
        return None
